package off_trial

import (
	sqlc "bp/db/sqlc"
	"bp/internal/render"
	sharedVld "bp/internal/rpcserver/shared/vld"
	"bp/internal/service/com/offer"
	"bp/internal/util"
	offTrialGrpc "bp/rpc/gen/mwebapi/off_trial"
	"context"
)

// ValidateTrialItem 验证offTrialGrpc.TrialItem
func ValidateTrialItem(v *offTrialGrpc.TrialItemEntity) (err error) {
	if util.IsEmpty(v.SceneDetailId) {
		err = render.InvalidArgumentRange("trial_item.scene_detail_id")
		return
	}
	if v.SceneDetailCnt <= 0 {
		err = render.InvalidArgumentRange("trial_item.scene_detail_cnt")
		return
	}
	if v.ItemId < 0 {
		err = render.InvalidArgumentRange("trial_item.item_id")
		return
	}
	if v.ItemSpecId < 0 {
		err = render.InvalidArgumentRange("trial_item.item_spec_id")
		return
	}
	if v.ItemPrice < 0 {
		err = render.InvalidArgumentRange("trial_item.item_price")
		return
	}
	return
}

// ValidateTrialOwner 验证offTrialGrpc.TrialOwner
func ValidateTrialOwner(v *offTrialGrpc.TrialOwnerEntity) (err error) {
	if v.OwnerId < 0 {
		err = render.InvalidArgumentRange("trial_owner.owner_id")
		return
	}
	for _, ti := range v.TrialItems {
		err = ValidateTrialItem(ti)
		if err != nil {
			return
		}
	}
	return
}

// VldDoTrialReq 验证优惠试算请求
func (s *OffTrialMWebApiImp) VldDoTrialReq(ctx context.Context, q *sqlc.Queries, req *offTrialGrpc.DoTrialReq) (toTrialOwnerPtrs []*offer.ToTrialOwner, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	if util.IsEmpty(req.OutTransNo) {
		err = render.InvalidArgumentRange("out_trans_no")
		return
	}
	if !sharedVld.IsOfferUseScene(req.TrialScene) {
		err = render.InvalidArgumentValue("trial_scene")
		return
	}
	if !sharedVld.IsIssuer(req.TrialIssuer) {
		err = render.InvalidArgumentValue("trial_issuer")
		return
	}
	if req.OutCardId < 0 {
		err = render.InvalidArgumentRange("out_card_id")
		return
	}
	if len(req.TrialOwners) == 0 {
		err = render.InvalidArgumentRange("trial_owners")
		return
	}
	for _, owner := range req.TrialOwners {
		err = ValidateTrialOwner(owner)
		if err != nil {
			return
		}
		toTrialOwnerPtrs = append(toTrialOwnerPtrs, s.ConvOffTrialOwnerPtrPbToEntity()(owner))
	}

	slog.Infof("off_trial_imp/cmd_vld.VldDoTrialReq ok")
	return
}
